package timesheet.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import timesheet.model.Event;
import timesheet.model.EventTime;
import timesheet.model.Project;
import timesheet.model.Users;
import timesheet.repository.EventRepository;
import timesheet.repository.EventTimeRepository;
import timesheet.repository.ProjectRepository;
import timesheet.repository.UserRepository;
import timesheet.web.ContextUtil;

@Controller
@Transactional
public class EventManagerController {
	@Autowired EventRepository eventRepository;
	@Autowired UserRepository userRepository;
	@Autowired ProjectRepository projectRepository;
	@Autowired EventTimeRepository eventTimeRepository;
	@RequestMapping("/eventmanager")
	public void eventManager(HttpServletRequest request, HttpServletResponse response) throws ParseException, JSONException{
		if((Long)ContextUtil.getHttpSession().getAttribute("UserId")!=null){
			java.text.DateFormat f = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			java.util.Date start = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(""+request.getParameter("start"));
			java.util.Date stop = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(""+request.getParameter("stop"));
			String description = (String)request.getParameter("desc");
			String section =  (String)request.getParameter("sect");
		    String project = (String)request.getParameter("pjt");
		    String comment = (String)request.getParameter("cmt");
		    String statut = (String)request.getParameter("status");
		    Users u = userRepository.findIdString(section);
		    Project p = projectRepository.findIdString(project);
			if("save".equals(request.getParameter("action"))){
				Event e =  new Event(start, stop, description,comment, u, p);
				e.setU(u);
				e.setP(p);
				long interval = ((e.getStopTime().getTime()) - (e.getStartTime().getTime()))/1000;
				e.setInterval(interval);
				eventRepository.createEvent(e);
			}
			else{
				Long id = Long.parseLong((String)request.getParameter("idDb"), 10);
				Event e = eventRepository.find(id);
				EventTime et = new EventTime();
				if("update".equals(request.getParameter("action"))){
					if("1".equals(statut)){
						if(eventTimeRepository.getLastEventTimeByEvent(e)!=null){
							et = eventTimeRepository.getLastEventTimeByEvent(e);
							if(et.getStop()!=null){
								e.setTask(description);
								e.setStartTime(start);
								e.setStopTime(stop);
								long interval = ((e.getStopTime().getTime()) - (e.getStartTime().getTime()))/1000;
								e.setInterval(interval);
								e.setU(u);
								e.setP(p);
								e.setCommentUser(comment);
								e.setStatut(statut);
								e.setU(u);
								e.setP(p);
							}
							else{
								JSONObject jsonobj = new JSONObject();
								String mess = "You have to stop this job before choosing planned";
								jsonobj.put("1",mess);
								try {
								jsonobj.write(response.getWriter());
								} catch (IOException i) {
									throw new RuntimeException("IOException in populateWithJSON", i);
								}
							}
						}
						else{
							e.setTask(description);
							e.setStartTime(start);
							e.setStopTime(stop);
							long interval = ((e.getStopTime().getTime()) - (e.getStartTime().getTime()))/1000;
							e.setInterval(interval);
							e.setU(u);
							e.setP(p);
							e.setCommentUser(comment);
							e.setStatut(statut);
							e.setU(u);
							e.setP(p);
						}
					}
					if("2".equals(statut)){
						String datestart = f.format(new Date());
						java.util.Date startAction = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(""+datestart);
						if(eventTimeRepository.getLastEventTimeByEvent(e)!=null){
							 et = eventTimeRepository.getLastEventTimeByEvent(e);
							if(et.getStop()!=null){
								et = new EventTime();
								e.setStatut(statut);
								et.setStart(startAction);
								et.setE(e);
								eventTimeRepository.merge(et);
							}
						}
						else{
							et = new EventTime();
							e.setStatut(statut);
							et.setStart(startAction);
							et.setE(e);
							eventTimeRepository.merge(et);
							}
						e.setCommentUser(comment);
					}
					if("3".equals(statut)){
						if(eventTimeRepository.getLastEventTimeByEvent(e)!=null){
							et = eventTimeRepository.getLastEventTimeByEvent(e);
							if(et.getStart()!= null && et.getStop() == null){
								String datestop = f.format(new Date());
								java.util.Date stopAction = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(""+datestop);
								et.setStop(stopAction);
								long interval = ((et.getStop().getTime()) - (et.getStart().getTime()))/1000;
								et.setInterval(interval);
								eventTimeRepository.merge(et);
								e.setStatut(statut);
							}
							else{
								e.setStatut("1");
								JSONObject jsonobj = new JSONObject();
								String mess = "You have to start this job before choosing finished";
								jsonobj.put("1",mess);
								try {
								jsonobj.write(response.getWriter());
								} catch (IOException i) {
									throw new RuntimeException("IOException in populateWithJSON", i);
								}
							}
						}
						else{
							e.setStatut("1");
							JSONObject jsonobj = new JSONObject();
							String mess = "You have to start this job before choosing finished";
							jsonobj.put("1",mess);
							try {
							jsonobj.write(response.getWriter());
							} catch (IOException i) {
								throw new RuntimeException("IOException in populateWithJSON", i);
							}
						}
						e.setCommentUser(comment);
					}
					eventRepository.merge(e);
				}
				else{
					if("delete".equals(request.getParameter("action"))){
						List<EventTime> timeList = (List<EventTime>) eventTimeRepository.getAllTimeByEvent(e);
						for(EventTime time : timeList){
							eventTimeRepository.remove(time);
						}
						eventRepository.remove(e);
					}
				}
			}
		}
	}
}




